import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { debounce, debounceTime, distinct, distinctUntilChanged, switchMap } from 'rxjs/operators';
import { PackageService } from './package-search.service';

export interface NpmPackageInfo {
    name: string;
    version: string;
    description: string;
}

@Component({
    selector: 'package-search',
    templateUrl: './package-search.component.html',
    providers: [
        PackageService
    ]
})

export class PackageSearchComponent implements OnInit {
    withRefresh = false;
    package$: Observable<NpmPackageInfo[]>;
    private searchText$ = new Subject<string>();

    search(packageName: string) {
        this.searchText$.next(packageName);
    }

    ngOnInit() {
        this.package$ = this.searchText$.pipe(
            debounceTime(500),
            distinctUntilChanged(),
            switchMap(packageName =>
                this.searchService.search(packageName, this.withRefresh)
            )
        );
    }
    constructor(
        private searchService: PackageService
    ) {}
}

